package com.book.shop.controller;

import com.book.shop.Webservice.OrderService;
import com.book.shop.Webservice.UserService;
import com.book.shop.model.Order;
import com.book.shop.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

import java.security.Principal;
import java.util.List;
import java.util.Objects;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;

    @GetMapping("/login")
    public String login(Principal principal){
        if(principal == null){
            return "login/login";
        }
            return "redirect:/";
    }
    //用户注册接口
    @GetMapping("/registration")
    public String registration(Model model){
        User user =new User();
        model.addAttribute("user",user);
        return "login/registration";
    }
    //用户注册接口
    @PostMapping("/registration")
    //@valid用于验证注解是否符合要求，直接加在变量user之前，
    // 在变量中添加验证信息的要求，当不符合要求时就会在方法中返回message的错误提示信息。
    public String createUser(@Valid User user, BindingResult bindingResult, Model model){
        User newUser = userService.findByUserName(user.getUserName());
        if(newUser != null){
            bindingResult.rejectValue("userName","error.user","用户已经存在");
        }
        if(!bindingResult.hasErrors()){
            userService.registerUser(user);
            model.addAttribute("successMessage","用户注册成功");
            model.addAttribute("user",new User());
        }
        return "login/registration";
    }
    //用户创建
    @PostMapping("/users")
    @Secured("ROLE_ADMIN")
    public String createUser(@RequestBody User user, Model model){
        if(user.getUserId()!=0){
            model.addAttribute("message","用户信息不存在");
        }else if(userService.findByUserName(user.getUserName())!= null){
            model.addAttribute("message","用户名存在");
        }else{
            userService.registerUser(user);
            model.addAttribute("message","用户创建成功");
        }
        return "edit/editUser";
    }
    //获取当前登录用户信息
    @GetMapping("/profile")
    public String getCurrentUser(Principal principal,Model model){
        if(principal == null){
            return "redirect:/";
        }
        User user = userService.findByUserName(principal.getName());
        model.addAttribute("user",user);
        return "edit/profile";
    }
    //更新用户信息
    @PostMapping("/profile")
    public String updateUser(@ModelAttribute User user,BindingResult bindingResult,Model model,Principal principal){
        User userExists= userService.findByUserName(user.getUserName());
        if(userExists != null&& !Objects.equals(userExists.getUserName(),principal.getName())){
            bindingResult.rejectValue("userName","error.user","用户名重复");
        }
        if(!bindingResult.hasErrors()){
            userService.updateUser(user);
            model.addAttribute("successMessage","用户信息更新成功");
        }
        return getCurrentUser(principal,model);
    }

    //获取所有用户信息查询接口
    @GetMapping("/users")
    @Secured("ROLE_ADMIN")
    public String getUsers(Model model){
        List<User> users = userService.findAllUsers();
        model.addAttribute("users",users);
        return "edit/showAllUsers";
    }
    //添加用户
    @GetMapping("/users/add")
    @Secured("ROLE_ADMIN")
    public String addUserPage(Model model){
        User user = new User();
        model.addAttribute("user",user);
        return "edit/addUser";
    }
    //添加用户
    @PostMapping("/users/add")
    @Secured("ROLE_ADMIN")
    public String addUser(@ModelAttribute User user, Model model, BindingResult bindingResult){
        User userExists = userService.findByUserName(user.getUserName());
        if(userExists!= null){
            bindingResult.rejectValue("userName","error.user","用户已存在");
        }
        if(!bindingResult.hasErrors()){
            User newUser =userService.registerUser(user);
            model.addAttribute("successMessage","创建用户成功，用户Id："+newUser.getUserId());
            model.addAttribute("user",new User());
        }
        return "edit/addUser";
    }
    //通过id编辑用户
    @GetMapping("/users/edit/{userId}")
    @Secured ("ROLE_ADMIN")
    public String editUserPage(@PathVariable Long userId, Model model){
        User user = userService.findUserById(userId);
        model.addAttribute("user", user);
        System.out.println(user);
        return "edit/editUser";
    }
    @PostMapping("/users/edit")
    @Secured ("ROLE_ADMIN")
    public String editUser(@ModelAttribute User user, Model model) {
        userService.updateUser(user);
        model.addAttribute("successMessage","用户更新"+user.getUserId());
        return editUserPage(user.getUserId(), model);
    }
    //通过id删除指定用户
    @GetMapping("/users/delete/{userId}")
    @Secured ("ROLE_ADMIN")
    public String deleteUser(@PathVariable Long userId, RedirectAttributes redirectAttributes){
        int userOrderAmount = userService.getUserOrderAmount(userId);
        if (userOrderAmount > 0) {
            redirectAttributes.addFlashAttribute("Message", "该用户名下有"+userOrderAmount+"条订单，不能删除");
//            model.addAttribute("Message", "该用户名下有"+userOrderAmount+"条订单，不能删除");
        }
        else{
            userService.deleteUserById(userId);
            redirectAttributes.addFlashAttribute("Message", "用户编号"+userId+"删除成功");
//            model.addAttribute("Message", "用户编号"+userId+"删除成功");
        }

        return "redirect:/users";
    }
//    //通过id编辑订单信息
//    @GetMapping("/users/edit/{userId}/complete0rder/{orderId}")
//    @Secured("ROLE_ADMIN")
//    public String completeOrder(@PathVariable Long orderId,
//                                @PathVariable Long userId, Model model){
//        Order order = orderService.findOrderById(orderId);
//        order.setOrderStatus (true);
//        orderService.update0rder(order);
//        model.addAttribute("successMessage","订单编号"+orderId +"完成");
//        return editUserPage (userId, model);
//    }
//    //通过orderid删除订单信息
//    @GetMapping("/users/edit/{userId}/delete0rder/{orderId}")
//    @Secured ("ROLE_ADMIN")
//    public String deleteOrder(@PathVariable Long orderId,
//                              @PathVariable Long userId, Model model) {
//        Order order = orderService.findOrderById(orderId);
//        orderService.deleteOrder (order);
//        model.addAttribute("successMessage","订单编号"+ orderId +"删除");
//        return editUserPage (userId, model);
//    }
    @GetMapping("/test")
    public String test(){
        return "test";
    }
}
